<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="搜索项">
              <a-input
                v-model:value="listQuery.title"
                placeholder="输入名称/ID搜索..."
                allowClear
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
            <a-form-item>
              <a-button
                v-permission="{ action: 'del_app_batch' }"
                type="primary"
                danger
                :disabled="selectedRowKeys.length === 0"
                @click="deleteSelect"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除所选
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0rem; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon><SyncOutlined /></template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'app_add' }"
              type="primary"
              style="margin-left: 0.75rem"
              @click="app_add"
            >
              <template #icon><PlusOutlined /></template> 新增APP
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="green">启用</a-tag>
        <a-tag v-if="record == 0" color="red">不启用</a-tag>
      </template>
      <template #qrcode="{ text: record }">
        <a-tooltip placement="top">
          <template #title>
            <span>APP下载页二维码</span>
          </template>
          <qrcode-outlined
            style="margin-left: 0.375rem; font-size: 1rem"
            @click="showQrcode(record)"
          />
        </a-tooltip>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'app_add' }" @click="app_edit(record)"><EditOutlined /> 编辑</a>
        <a-divider v-permission="{ action: 'app_upgrade' }" type="vertical" />
        <a v-permission="{ action: 'app_upgrade' }" @click="app_upgrade(record)"> 版本升级</a>
        <a-divider v-permission="{ action: 'app_ext' }" type="vertical" />
        <a-dropdown>
          <a v-permission="{ action: 'app_ext' }" class="ant-dropdown-link">
            更多 <DownOutlined
          /></a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'app_copy' }">
                <a @click="app_copy(record)"><CopyOutlined /> 复用</a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'del_app' }" style="color: red">
                <a @click="app_delete(record)"><DeleteOutlined /> 删除</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-drawer
      width="50%"
      title="APP详情"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 0.5rem"
          @click="
            () => {
              drawerShow = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" :loading="submitLoading" @click="addItem">提交</a-button>
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item label="APP名称" has-feedback required name="title">
          <a-input v-model:value="FormState.title" placeholder="请输入APP名称" />
        </a-form-item>
        <a-form-item label="App Scheme" name="scheme">
          <a-input
            v-model:value="FormState.scheme"
            placeholder="请输入App Scheme，如: ningmengapp://"
          />
        </a-form-item>
        <a-form-item label="APP上传配置" has-feedback required name="fs_id">
          <a-tooltip placement="top">
            <template #title>
              <span
                >如下拉为空，请先通过“文件存储管理”-“文件存储配置”-“新增文件存储配置”进行添加后再进行选择</span
              >
            </template>
            <a-select v-model:value="FormState.fs_id" placeholder="请选择APP上传配置">
              <a-select-option v-for="d in allFileServer" :key="d._id" :value="d._id">
                {{ d.title }}
              </a-select-option>
              <template #notFoundContent>
                <a-empty
                  image="https://img.alicdn.com/imgextra/i3/573804794/O1CN01IO097G1lHhdtoisyG_!!573804794.png"
                  :image-style="{
                    height: '90px'
                  }"
                >
                  <template #description>
                    <view style="color: rgba(0, 0, 0, 0.88); padding-top: 20px">
                      暂无可选项，请先
                      <router-link :to="{ name: 'fileServer' }" target="_blank">添加</router-link>
                    </view>
                  </template>
                </a-empty>
              </template>
            </a-select>
          </a-tooltip>
        </a-form-item>
        <a-form-item label="APP上传分类" has-feedback required name="fc_id">
          <a-tooltip placement="top">
            <template #title>
              <span
                >如下拉为空，请先通过“文件存储管理”-“文件分类”-“新增分类”进行添加后再进行选择</span
              >
            </template>
            <a-select v-model:value="FormState.fc_id" placeholder="请选择APP上传分类">
              <a-select-option v-for="d in allFileCate" :key="d._id" :value="d._id">
                {{ d.title }}
              </a-select-option>
              <template #notFoundContent>
                <a-empty
                  image="https://img.alicdn.com/imgextra/i3/573804794/O1CN01IO097G1lHhdtoisyG_!!573804794.png"
                  :image-style="{
                    height: '90px'
                  }"
                >
                  <template #description>
                    <view style="color: rgba(0, 0, 0, 0.88); padding-top: 20px">
                      暂无可选项，请先
                      <router-link :to="{ name: 'fileCate' }" target="_blank">添加</router-link>
                    </view>
                  </template>
                </a-empty>
              </template>
            </a-select>
          </a-tooltip>
        </a-form-item>
        <a-form-item label="APP图标" name="icon">
          <div style="display: flex; align-items: center">
            <div
              style="
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: center;
                border: 0.0625rem solid #d9d9d9;
                width: 6.25rem;
                height: 6.25rem;
                background-color: #fafafa;
                margin-right: 0.5rem;
                margin-top: -0.4375rem;
              "
            >
              <a-image
                v-if="FormState.icon"
                :src="FormState.icon"
                alt="APP图标"
                :height="100"
                :width="100"
              />
            </div>
            <a-tooltip placement="top" title="请上传.svg/.png格式的图片">
              <a-upload
                name="file"
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                accept=".svg,.png"
                :action="apiUrl + 'api/common/uploadFileWithServer'"
                :data="uploadData"
                :headers="uploadHeaders"
                :beforeUpload="beforeUploadIcon"
                @change="uploadChangeIcon"
              >
                <div>
                  <loading-outlined v-if="uploadLoadingIcon" />
                  <plus-outlined v-else />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-tooltip>
          </div>
        </a-form-item>
        <a-form-item label="下载页背景" has-feedback required name="bg_type">
          <a-radio-group v-model:value="FormState.bg_type" name="bg_type">
            <a-radio :key="1" :value="1">自定义</a-radio>
            <a-radio :key="0" :value="0">默认</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="FormState.bg_type === 1" label="自定义背景图" name="bg_pic">
          <div style="display: flex; align-items: center">
            <div
              style="
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: center;
                border: 0.0625rem solid #d9d9d9;
                width: 6.25rem;
                height: 6.25rem;
                background-color: #fafafa;
                margin-right: 0.5rem;
                margin-top: -0.4375rem;
              "
            >
              <a-image
                v-if="FormState.bg_pic"
                :src="FormState.bg_pic"
                alt="APP下载页背景图"
                :height="100"
                :width="100"
              />
            </div>
            <a-upload
              name="file"
              listType="picture-card"
              class="avatar-uploader"
              accept=".png,.jpg,.jpeg"
              :showUploadList="false"
              :action="apiUrl + 'api/common/uploadFileWithServer'"
              :data="uploadData"
              :headers="uploadHeaders"
              :beforeUpload="beforeUploadBgPic"
              @change="uploadChangeBgPic"
            >
              <div>
                <loading-outlined v-if="uploadLoadingBgPic" />
                <plus-outlined v-else />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="下载页按钮色" name="btn_color">
          <ColorPicker
            theme="light"
            :color="FormState.btn_color"
            :sucker-hide="true"
            @changeColor="changeColor"
          />
        </a-form-item>
        <a-form-item label="SecretKey" name="server_secret">
          <a-tooltip title="双击可复制，请妥善保管">
            <a-input-search
              v-model:value="FormState.server_secret"
              placeholder="点击右侧“获取密钥”按钮进行获取"
              enter-button="获取密钥"
              @search="resetSecret"
              @dblclick="copyText(FormState.server_secret)"
            />
          </a-tooltip>
        </a-form-item>
        <a-form-item label="状态" has-feedback required name="status">
          <a-radio-group v-model:value="FormState.status" name="status">
            <a-radio :key="1" :value="1">启用</a-radio>
            <a-radio :key="0" :value="0">不启用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="备注" name="desc">
          <a-textarea
            v-model:value="FormState.desc"
            show-count
            placeholder="(可选)"
            :autoSize="{ minRows: 2, maxRows: 6 }"
          />
        </a-form-item>
        <a-form-item v-if="FormState._id" label="下载落地页">
          <a-textarea
            :value="'https://plus.21ds.cn/download/app/' + FormState._id"
            readonly
            @click="copyText('https://plus.21ds.cn/download/app/' + FormState._id)"
          />
        </a-form-item>
      </a-form>
    </a-drawer>
    <a-drawer
      width="80%"
      :title="'【' + selectApp['title'] + '】APP版本列表'"
      placement="right"
      :open="drawerShowVersion"
      @close="
        () => {
          drawerShowVersion = false
        }
      "
    >
      <template #extra>
        <a-tooltip placement="top">
          <template #title>
            <span>刷新列表</span>
          </template>
          <a-button @click="reloadListVersion">
            <template #icon><SyncOutlined /></template>
          </a-button>
        </a-tooltip>
        <a-button
          v-permission="{ action: 'del_app_version_batch' }"
          type="primary"
          danger
          :disabled="selectedRowKeysVersion.length === 0"
          style="margin-left: 0.75rem"
          @click="deleteSelectVersion"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          删除所选
        </a-button>
        <a-button
          v-permission="{ action: 'app_version_add' }"
          type="primary"
          style="margin-left: 0.75rem"
          @click="app_version_add"
        >
          <template #icon><PlusOutlined /></template> 增加新版本
        </a-button>
      </template>
      <a-table
        :columns="columnsVersion"
        :rowKey="(record) => record._id"
        :dataSource="dataVersionList.data"
        :loading="loadingVersion"
        :pagination="paginationVersion"
        :row-selection="{
          selectedRowKeys: selectedRowKeysVersion,
          onChange: onSelectChangeVersion
        }"
        @change="handleTableChangeVersion"
      >
        <template #status="{ text: record }">
          <a-tooltip placement="top">
            <template #title>
              <span>每个APP中每个版本及更新类型仅可只有一个上线发行版本</span>
            </template>
            <a-switch :checked="record.status" @click="changeStatus(record)" />
          </a-tooltip>
        </template>
        <template #force="{ text: record }">
          <a-switch :checked="record.force" @click="changeForce(record)" />
        </template>
        <template #version_type="{ text: record }">
          <a-tag v-if="record == 'neice'" color="orange">内部测试版</a-tag>
          <a-tag v-if="record == 'gongce'" color="blue">公开测试版</a-tag>
          <a-tag v-if="record == 'zhengshi'" color="green">正式版</a-tag>
        </template>
        <template #upgrade_type="{ text: record }">
          <a-tag v-if="record == 'incr'" color="cyan">增量</a-tag>
          <a-tag v-if="record == 'all'" color="blue">全量</a-tag>
        </template>
        <template #action="{ text: record }">
          <a v-permission="{ action: 'app_version_add' }" @click="app_version_edit(record)"
            ><EditOutlined /> 编辑</a
          >
          <a-divider v-permission="{ action: 'app_version_copy' }" type="vertical" />
          <a v-permission="{ action: 'app_version_copy' }" @click="app_version_copy(record)"
            ><CopyOutlined /> 复制</a
          >
          <a-divider v-permission="{ action: 'app_version_delete' }" type="vertical" />
          <a
            v-permission="{ action: 'app_version_delete' }"
            style="color: red"
            @click="app_version_delete(record)"
            ><DeleteOutlined /> 删除</a
          >
        </template>
      </a-table>
    </a-drawer>
    <a-drawer
      width="50%"
      title="APP版本详情"
      placement="right"
      :open="drawerShowVersionInfo"
      @close="
        () => {
          drawerShowVersionInfo = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 0.5rem"
          @click="
            () => {
              drawerShowVersionInfo = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" :loading="submitVersionLoading" @click="addVersionItem"
          >提交</a-button
        >
      </template>
      <a-form
        ref="formRefVersion"
        :model="FormStateVersion"
        :rules="FormRuleVersion"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item label="版本类型" has-feedback required name="version_type">
          <a-radio-group v-model:value="FormStateVersion.version_type" :options="versionOptions" />
        </a-form-item>
        <a-form-item label="更新类型" has-feedback required name="upgrade_type">
          <a-radio-group v-model:value="FormStateVersion.upgrade_type" :options="typeOptions" />
        </a-form-item>
        <a-form-item label="平台类型" has-feedback required name="platform">
          <a-checkbox-group v-model:value="FormStateVersion.platform" :options="platformOptions" />
        </a-form-item>
        <a-form-item label="更新标题" has-feedback required name="upgrade_title">
          <a-input v-model:value="FormStateVersion.upgrade_title" placeholder="更新标题" />
        </a-form-item>
        <a-form-item label="更新内容" has-feedback required name="upgrade_content">
          <a-textarea
            v-model:value="FormStateVersion.upgrade_content"
            show-count
            placeholder="请输入更新内容"
            :autoSize="{ minRows: 2, maxRows: 6 }"
          />
        </a-form-item>
        <a-form-item label="提醒周期(小时)" has-feedback required name="notice_cycle">
          <a-tooltip placement="top">
            <template #title>
              <span>单位：小时。设置提醒周期后，周期内仅提醒一次，避免频繁提醒给用户造成困扰</span>
            </template>
            <a-input-number
              v-model:value="FormStateVersion.notice_cycle"
              placeholder="请输入提醒周期，周期内仅提醒一次，避免频繁提醒给用户造成困扰"
              style="width: 100%"
            />
          </a-tooltip>
        </a-form-item>
        <a-form-item
          v-if="FormStateVersion.upgrade_type == 'incr'"
          label="[增量]版本号"
          name="version_incr"
          has-feedback
          required
        >
          <a-input-number
            v-model:value="FormStateVersion.version_incr"
            placeholder="请输入增量版本号"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item
          v-if="FormStateVersion.upgrade_type == 'incr'"
          label="[增量]增量包地址"
          has-feedback
          required
        >
          <a-textarea
            v-model:value="FormStateVersion.incr_url"
            show-count
            placeholder="请输入下载链接"
            :autoSize="{ minRows: 2, maxRows: 6 }"
            style="margin-bottom: 0.625rem"
          /><a-upload
            name="file"
            :action="apiUrl + 'api/common/uploadFileWithServer'"
            :headers="uploadHeaders"
            :data="uploadData"
            :beforeUpload="beforeUpload"
            :disabled="uploadLoading"
            @change="uploadChangeIncr"
          >
            <a-button v-if="!uploadLoading" :loading="uploadLoading"> 选择文件 </a-button>
            <a-button v-else :loading="uploadLoading"> 已上传: {{ uploadIncr }}% </a-button>
          </a-upload>
        </a-form-item>
        <div
          v-if="
            inArray('android', FormStateVersion.platform) && FormStateVersion.upgrade_type == 'all'
          "
          class="area_block"
        >
          <a-form-item
            v-if="
              inArray('android', FormStateVersion.platform) &&
              FormStateVersion.upgrade_type == 'all'
            "
            label="[安卓]版本号"
            name="version_no_android"
            required
          >
            <a-input-number
              v-model:value="FormStateVersion.version_no_android"
              placeholder="请输入安卓版本号"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item
            v-if="
              inArray('android', FormStateVersion.platform) &&
              FormStateVersion.upgrade_type == 'all'
            "
            label="[安卓]上传软件包"
          >
            <a-upload
              name="file"
              :action="apiUrl + 'api/common/uploadFileWithServer'"
              :headers="uploadHeaders"
              :data="uploadData"
              :beforeUpload="beforeUpload"
              :disabled="uploadLoading"
              @change="uploadChange"
            >
              <a-button v-if="!uploadLoading" :loading="uploadLoading"> 选择文件 </a-button>
              <a-button v-else :loading="uploadLoading"> 已上传: {{ uploadIncr }}% </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item
            v-if="
              inArray('android', FormStateVersion.platform) &&
              FormStateVersion.upgrade_type == 'all'
            "
            label="[安卓]下载链接"
            name="url_android"
            required
          >
            <a-textarea
              v-model:value="FormStateVersion.url_android"
              show-count
              placeholder="请输入下载链接"
              :autoSize="{ minRows: 2, maxRows: 6 }"
            />
          </a-form-item>
          <a-form-item
            v-if="
              inArray('android', FormStateVersion.platform) &&
              FormStateVersion.upgrade_type == 'all'
            "
            label="[安卓]应用市场链接"
            name="store_url_android"
          >
            <a-textarea
              v-model:value="FormStateVersion.store_url_android"
              show-count
              placeholder="请输入应用市场链接"
              :autoSize="{ minRows: 2, maxRows: 6 }"
            />
          </a-form-item>
        </div>
        <div
          v-if="inArray('ios', FormStateVersion.platform) && FormStateVersion.upgrade_type == 'all'"
          class="area_block"
        >
          <a-form-item
            v-if="
              inArray('ios', FormStateVersion.platform) && FormStateVersion.upgrade_type == 'all'
            "
            label="[苹果]版本号"
            name="version_no_ios"
            required
          >
            <a-input-number
              v-model:value="FormStateVersion.version_no_ios"
              placeholder="请输入苹果版本号"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item
            v-if="
              inArray('ios', FormStateVersion.platform) && FormStateVersion.upgrade_type == 'all'
            "
            label="[苹果]下载链接"
            name="url_ios"
            required
          >
            <a-textarea
              v-model:value="FormStateVersion.url_ios"
              show-count
              placeholder="请输入APP Store下载链接"
              :autoSize="{ minRows: 2, maxRows: 6 }"
            />
          </a-form-item>
        </div>
        <a-form-item label="强制更新" name="force">
          <a-switch v-model:checked="FormStateVersion.force" />
        </a-form-item>
        <a-form-item label="上线发行" name="status">
          <a-switch v-model:checked="FormStateVersion.status" />
        </a-form-item>
        <a-form-item label="备注" name="desc">
          <a-textarea
            v-model:value="FormStateVersion.desc"
            show-count
            placeholder="(可选)"
            :autoSize="{ minRows: 2, maxRows: 6 }"
          />
        </a-form-item>
      </a-form>
    </a-drawer>
    <a-modal
      v-model:open="oauthVisible"
      title="APP落地页二维码"
      :width="450"
      :footer="null"
      :forceRender="true"
      @cancel="
        () => {
          oauthVisible = false
        }
      "
    >
      <div id="qrcode_div" ref="qrCodeRefs2" style="padding-bottom: 0.9375rem">
        <a-qrcode
          ref="qrCodeRefs"
          :value="'https://plus.21ds.cn/download/app/' + qrcodeData._id"
          :icon="qrcodeData.icon"
          size="400"
          iconSize="80"
          bgColor="#ffffff"
        />
        <div style="width: 100%; text-align: center; font-size: 1.0625rem; margin-top: 0.625rem">
          {{ qrcodeData.title }}
        </div>
      </div>
      <div style="display: flex; flex-direction: column; align-items: center">
        <!-- <a-button @click="downQrcode">下载二维码</a-button> -->
        <span style="margin-top: 0.625rem; font-size: 0.8125rem; color: red"
          >注：在二维码上右键，选择“图片另存为”进行保存</span
        >
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { ColorPicker } from 'vue-color-kit'
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Drawer,
  Card,
  Tooltip,
  Statistic,
  RadioGroup,
  QRCode,
  RangePicker,
  Switch,
  InputNumber,
  Image,
  Upload
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  CopyOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  QrcodeOutlined,
  ExclamationCircleOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import {
  delAppItem,
  delAppVersionItem,
  getAppList,
  editAppInfo,
  editVersionInfo,
  delAppBatch,
  delAppVersionBatch,
  changeStatusVersion,
  changeForceVersion,
  getAppVersionList
} from '@/api/app'
import { useRouter } from 'vue-router'
import { todayDate, randomString } from '@/utils/common'
import { getAllServerList, getAllCateList } from '@/api/file'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { storage } from '@/utils/Storage'
import { apiUrl, inArray, copyText } from '@/utils/common'
import html2canvas from 'html2canvas'

export default defineComponent({
  name: 'Upgrade',
  components: {
    SyncOutlined,
    PlusOutlined,
    QrcodeOutlined,
    EditOutlined,
    ColorPicker,
    CopyOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    DownOutlined,
    DeleteOutlined,
    [Upload.name]: Upload,
    [Image.name]: Image,
    [Switch.name]: Switch,
    [Row.name]: Row,
    [InputNumber.name]: InputNumber,
    [Card.name]: Card,
    [Tooltip.name]: Tooltip,
    [RadioGroup.name]: RadioGroup,
    [RangePicker.name]: RangePicker,
    [QRCode.name]: QRCode,
    [Divider.name]: Divider,
    [Statistic.name]: Statistic,
    [Drawer.name]: Drawer,
    [Col.name]: Col
  },
  setup() {
    const formRef = ref()
    const formRefVersion = ref()
    const router = useRouter()
    const state = reactive<any>({
      uploadHeaders: {},
      uploadData: {},
      uploadLoading: false,
      oauthVisible: false,
      uploadLoadingIcon: false,
      qrcodeData: {},
      uploadLoadingBgPic: false,
      apiUrl: apiUrl(),
      loading: true,
      loadingVersion: true,
      drawerShow: false,
      uploadIncr: 0,
      drawerShowVersion: false,
      drawerShowVersionInfo: false,
      submitVersionLoading: false,
      submitLoading: false,
      today: todayDate(),
      dataList: [],
      fileList: [],
      dataVersionList: [],
      allFileServer: [],
      selectedRowKeys: [],
      selectedKeysPage: {},
      selectedRowKeysVersionPage: {},
      selectedRowKeysVersion: [],
      platformOptions: [
        { label: '安卓', value: 'android' },
        { label: '苹果', value: 'ios' }
      ],
      typeOptions: [
        { label: '全量更新', value: 'all' },
        { label: '增量更新', value: 'incr' }
      ],
      versionOptions: [
        { label: '内部测试版(neice)', value: 'neice' },
        { label: '公开测试版(gongce)', value: 'gongce' },
        { label: '正式版(zhengshi)', value: 'zhengshi' }
      ],
      allFileCate: [],
      selectApp: {},
      totalData: {},
      allLineRender: '',
      singleLineRender: '',
      ticketLineRender: '',
      dataTime: '',
      allLine: ref(),
      singleLine: ref(),
      ticketLine: ref(),
      activeKey: ref('1'),
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        date_range: [],
        date_range_format: [],
        date_num: -1
      },
      listQueryVersion: {
        app_id: '',
        date_num: 0
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      paginationVersion: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      columns: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: 'APP名称',
          dataIndex: 'title'
        },
        {
          title: '二维码',
          slots: { customRender: 'qrcode' }
        },
        {
          title: '文件存储配置',
          dataIndex: 'fs_title'
        },
        {
          title: '文件存储分类',
          dataIndex: 'fc_title'
        },
        {
          title: '状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '备注',
          dataIndex: 'desc'
        },
        {
          title: '操作',
          width: '15rem',
          slots: { customRender: 'action' }
        }
      ],
      columnsVersion: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: '更新标题',
          dataIndex: 'upgrade_title'
        },
        {
          title: '版本类型',
          dataIndex: 'version_type',
          slots: { customRender: 'version_type' }
        },
        {
          title: '更新类型',
          dataIndex: 'upgrade_type',
          slots: { customRender: 'upgrade_type' }
        },
        {
          title: '[增量]版本号',
          dataIndex: 'version_incr'
        },
        {
          title: '[安卓]版本号',
          dataIndex: 'version_no_android'
        },
        {
          title: '[苹果]版本号',
          dataIndex: 'version_no_ios'
        },
        {
          title: '强制更新',
          slots: { customRender: 'force' }
        },
        {
          title: '上线发行',
          slots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '备注',
          dataIndex: 'desc'
        },
        {
          title: '操作',
          width: '13.75rem',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getDataList()
      getServerDataList()
    })
    function getServerDataList() {
      getAllServerList({}).then((res) => {
        state.allFileServer = res
      })
      getAllCateList({}).then((res) => {
        state.allFileCate = res
      })
    }
    function resetSecret() {
      FormState.server_secret = randomString(64)
    }

    const FormState = reactive<any>({
      title: '',
      fs_id: '',
      icon: '',
      bg_pic: '',
      scheme: '',
      btn_color: '',
      status: '',
      server_secret: '',
      fc_id: ''
    })
    const FormRule = {
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
      bg_pic: [{ required: false, message: '请输入标题', trigger: ['blur', 'change'] }],
      fc_id: [{ required: true, message: '请选择文件存储分类', trigger: ['blur', 'change'] }],
      status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }],
      server_secret: [{ required: true, message: '请先获取密钥', trigger: ['blur', 'change'] }],
      fs_id: [{ required: true, message: '请选择文件存储配置', trigger: ['blur', 'change'] }]
    }

    const FormStateVersion = reactive({
      platform: [''],
      upgrade_title: '',
      upgrade_content: '',
      store_url_android: '',
      version_type: '',
      notice_cycle: '',
      upgrade_type: '',
      version_incr: '',
      incr_url: '',
      app_id: '',
      status: false,
      force: false,
      version_no_android: null,
      url_android: '',
      url_ios: null,
      version_no_ios: null,
      desc: ''
    })
    const FormRuleVersion = {
      platform: [{ required: true, message: '请选择平台类型', trigger: ['blur', 'change'] }],
      upgrade_type: [{ required: true, message: '请选择更新类型', trigger: ['blur', 'change'] }],
      notice_cycle: [{ required: true, message: '请输入提醒周期', trigger: ['blur', 'change'] }],
      upgrade_title: [{ required: true, message: '请输入更新标题', trigger: ['blur', 'change'] }],
      upgrade_content: [{ required: true, message: '请输入更新内容', trigger: ['blur', 'change'] }]
    }

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }
    function handleTableChangeVersion(e) {
      state.loadingVersion = true
      state.paginationVersion.pageSize = e.pageSize
      state.listQueryVersion.pageSize = e.pageSize
      state.listQueryVersion.pageNo = e.current
      state.paginationVersion.current = e.current
      dataVersionListData()
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function reloadListVersion() {
      state.loadingVersion = true
      state.listQueryVersion.pageNo = 1
      dataVersionListData()
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function app_edit(res) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function app_version_edit(res) {
      for (let item in FormStateVersion) {
        FormStateVersion[item] = ''
      }
      for (let item in res) {
        FormStateVersion[item] = res[item]
      }
      state.drawerShowVersionInfo = true
    }
    function app_version_copy(res) {
      for (let item in FormStateVersion) {
        FormStateVersion[item] = ''
      }
      for (let item in res) {
        if (item === 'upgrade_title') {
          FormStateVersion[item] = res[item] + ' - 复制'
        } else if (item === '_id' || item === 'id') {
          FormStateVersion[item] = ''
        } else {
          FormStateVersion[item] = res[item]
        }
      }
      state.drawerShowVersionInfo = true
    }
    function app_copy(res) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        if (item != '_id' && item != 'server_secret') {
          let copyTips = item == 'title' ? ' - 复制' : ''
          FormState[item] = res[item] + copyTips
        }
      }
      state.drawerShow = true
    }
    function app_add() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerShow = true
    }
    function app_version_add() {
      for (let item in FormStateVersion) {
        FormStateVersion[item] = ''
      }
      state.drawerShowVersionInfo = true
    }
    function app_upgrade(item) {
      state.drawerShowVersion = true
      state.selectApp = item
      state.listQueryVersion.app_id = item._id
      dataVersionListData()
    }

    function getDataList() {
      getAppList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    function dataVersionListData() {
      getAppVersionList(state.listQueryVersion).then((res) => {
        state.loadingVersion = false
        state.dataVersionList = res
        state.paginationVersion.total = res.totalCount
      })
    }
    const addItem = () => {
      formRef.value
        .validate()
        .then(() => {
          state.submitLoading = true
          editAppInfo(toRaw(FormState))
            .then((res) => {
              if (res.code === 200) {
                requestSuccess(res)
                formRef.value.resetFields()
                state.loading = true
                state.drawerShow = false
                reloadList()
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.submitLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    const addVersionItem = () => {
      formRefVersion.value
        .validate()
        .then(() => {
          state.submitVersionLoading = true
          FormStateVersion.app_id = state.selectApp._id
          editVersionInfo(toRaw(FormStateVersion))
            .then((res) => {
              if (res.code === 200) {
                requestSuccess(res)
                formRefVersion.value.resetFields()
                state.loadingVersion = true
                state.drawerShowVersionInfo = false
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.submitVersionLoading = false
              reloadListVersion()
            })
        })
        .catch(() => {
          return false
        })
    }
    function app_delete(data) {
      Modal.confirm({
        title: '确认删除此APP?',
        content: '【' + data.title + '】(注：删除APP时会一同删除该APP下所有版本项)',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delAppItem({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function app_version_delete(data) {
      Modal.confirm({
        title: '确认删除此版本?',
        content: '【' + data.upgrade_title + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delAppVersionItem({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loadingVersion = true
              reloadListVersion()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function deleteSelect() {
      Modal.confirm({
        title: '确认批量删除所选APP?',
        content: '注：删除APP时会一同删除该APP下所有版本项',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delAppBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    function deleteSelectVersion() {
      Modal.confirm({
        title: '确认批量删除所选版本?',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          state.loadingVersion = true
          delAppVersionBatch({ ids: state.selectedRowKeysVersion })
            .then((res) => {
              if (res.code === 200) {
                reloadListVersion()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeysVersion = []
            })
        }
      })
    }
    const onSelectChange = (selectedRowKeys) => {
      state.selectedKeysPage[state.listQuery.pageNo] = selectedRowKeys
      let nowList: any[] = []
      for (const key in state.selectedKeysPage) {
        nowList = nowList.concat(state.selectedKeysPage[key])
      }
      const uniqueList = [...new Set(nowList)]
      state.selectedRowKeys = uniqueList
    }
    const onSelectChangeVersion = (selectedRowKeys: []) => {
      state.selectedRowKeysVersionPage[state.listQuery.pageNo] = selectedRowKeys
      let nowList: any[] = []
      for (const key in state.selectedRowKeysVersionPage) {
        nowList = nowList.concat(state.selectedRowKeysVersionPage[key])
      }
      const uniqueList = [...new Set(nowList)]
      state.selectedRowKeysVersion = uniqueList
    }
    function uploadChange(info) {
      if (info.file.status === 'uploading') {
        state.uploadLoading = true
        state.uploadIncr = info.file.percent
        return
      }
      if (info.file.status === 'done') {
        state.uploadLoading = false
        if (info.file.response.code == 200) {
          FormStateVersion.url_android = info.file.response.data[0].url
        } else {
          requestFailed(info.file.response)
        }
      }
    }
    function uploadChangeIncr(info) {
      if (info.file.status === 'uploading') {
        state.uploadLoading = true
        state.uploadIncr = info.file.percent
        return
      }
      if (info.file.status === 'done') {
        state.uploadLoading = false
        if (info.file.response.code == 200) {
          FormStateVersion.incr_url = info.file.response.data[0].url
        }
      }
    }
    function beforeUpload() {
      const token = storage.get(ACCESS_TOKEN)
      if (token) {
        state.uploadHeaders['Authorization'] = 'Bearer ' + token + ':' + new Date().getTime() // 让每个请求携带token
      }
      state.uploadData = state.selectApp
      FormStateVersion['url_android'] = ''
      return true
    }
    function uploadChangeBgPic(info) {
      if (info.file.status === 'uploading') {
        state.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        state.uploadLoading = false
        if (info.file.response.code == 200) {
          FormState['bg_pic'] = info.file.response.data[0].url
        }
      }
    }
    function beforeUploadBgPic() {
      const token = storage.get(ACCESS_TOKEN)
      if (token) {
        state.uploadHeaders['Authorization'] = 'Bearer ' + token + ':' + new Date().getTime() // 让每个请求携带token
      }
      if (
        FormState.fs_id == undefined ||
        FormState.fs_id.length == 0 ||
        FormState.fc_id == undefined ||
        FormState.fc_id.length == 0
      ) {
        requestFailed(null, '请先选择上传配置及上传分类')
        return false
      }
      state.uploadData = FormState
      FormState['bg_pic'] = ''
      return true
    }
    function uploadChangeIcon(info) {
      if (info.file.status === 'uploading') {
        state.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        state.uploadLoading = false
        if (info.file.response.code == 200) {
          FormState['icon'] = info.file.response.data[0].url
        }
      }
    }
    function beforeUploadIcon() {
      const token = storage.get(ACCESS_TOKEN)
      if (token) {
        state.uploadHeaders['Authorization'] = 'Bearer ' + token + ':' + new Date().getTime() // 让每个请求携带token
      }
      if (
        FormState.fs_id == undefined ||
        FormState.fs_id.length == 0 ||
        FormState.fc_id == undefined ||
        FormState.fc_id.length == 0
      ) {
        requestFailed(null, '请先选择上传配置及上传分类')
        return false
      }
      state.uploadData = FormState
      FormState['icon'] = ''
      return true
    }
    function changeForce(e) {
      state.loadingVersion = true
      changeForceVersion({ id: e._id }).then((res) => {
        if (res.code === 200) {
          reloadListVersion()
          requestSuccess(res)
        } else {
          requestFailed(res)
        }
      })
    }
    function changeStatus(e) {
      state.loadingVersion = true
      changeStatusVersion({ id: e._id })
        .then((res) => {
          if (res.code === 200) {
            requestSuccess(res)
          } else {
            requestFailed(res)
          }
        })
        .finally(() => {
          reloadListVersion()
        })
    }
    const visibleBgPic = ref<boolean>(false)
    const setVisible = (value): void => {
      visibleBgPic.value = value
    }

    const downQrcode = () => {
      let qrHtml = document.getElementById('qrcode_div') as HTMLElement
      html2canvas(qrHtml).then(function (canvas) {
        let base64Img = canvas.toDataURL('image/png')
        const a = document.createElement('a')
        a.href = base64Img
        a.setAttribute('download', state.qrcodeData._id)
        a.click()
      })
    }
    function changeColor(hex) {
      FormState.btn_color = hex.hex
    }
    function showQrcode(record) {
      state.qrcodeData = record
      state.oauthVisible = true
    }
    return {
      ...toRefs(state),
      visibleBgPic,
      setVisible,
      downQrcode,
      beforeUploadIcon,
      showQrcode,
      changeColor,
      uploadChangeIcon,
      uploadChange,
      uploadChangeIncr,
      beforeUpload,
      beforeUploadBgPic,
      uploadChangeBgPic,
      handleTableChange,
      handleTableChangeVersion,
      app_version_edit,
      app_version_delete,
      app_version_copy,
      deleteSelect,
      deleteSelectVersion,
      changeStatus,
      changeForce,
      FormRuleVersion,
      FormStateVersion,
      onSelectChange,
      copyText,
      reloadList,
      reloadListVersion,
      searchSubmit,
      app_delete,
      formRef,
      formRefVersion,
      app_add,
      onSelectChangeVersion,
      addVersionItem,
      app_version_add,
      resetSecret,
      FormState,
      app_edit,
      app_upgrade,
      inArray,
      addItem,
      FormRule,
      app_copy,
      router,
      getDataList
    }
  }
})
</script>

<style>
.ant-upload-wrapper .ant-upload-list {
  display: none !important;
}
</style>
